/*
 * FileName: MyBatisUtil.java
 * Author:   zzw
 * Date:     2018年08月17日
 * Description:
 */
package com.zzw.utils;

import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 〈〉<br>
 * 〈〉
 *
 * @author zzw
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本]（可选）
 */
public class MyBatisUtil {

    private static Logger logger = LoggerFactory.getLogger(MyBatisUtil.class);
    private static String driver = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://172.16.12.33:30014/csfmonitora";
    private static String username = "root";
    private static String password = "mychebao";
    private static PooledDataSource dataSource = new PooledDataSource(driver, url, username, password);
    private static TransactionFactory transactionFactory = new JdbcTransactionFactory();
    private static Environment environment = new Environment("development", transactionFactory, dataSource);
    private static Configuration configuration = new Configuration(environment);
    private static Map<String,String> mapperList = new HashMap<>();
    private static SqlSessionFactory factory  = new SqlSessionFactoryBuilder().build(configuration);
    private static SqlSession sqlSession = factory.openSession();

    static {
        logger.warn("MyBatisUtil static .....");
        //mapperList.put("mapper/AppMapper.xml",AppMapper.class.getName());
        //mapperList.put("mapper/AppUserRelatedMapper.xml",AppUserRelatedMapper.class.getName());
        //mapperList.put("mapper/UserMapper.xml",UserMapper.class.getName());

        InputStream inputStream2 = null;
        for (Map.Entry<String,String> entry:mapperList.entrySet()){
            try {
                inputStream2 = Resources.getResourceAsStream(Thread.currentThread().getContextClassLoader(), entry.getKey());
            } catch (IOException e) {
                logger.error("getResourceAsStream error");
            }
            if(inputStream2 != null){
                XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream2, configuration, entry.getKey(), configuration.getSqlFragments(), entry.getValue());
                xmlParser.parse();
            }
        }
    }

    public static Object getMapper(Class clazz){
        Object mapper = sqlSession.getMapper(clazz);
        return mapper;
    }
}
